<template>
    <el-upload
        action="#"
        list-type="picture-card"
        :auto-upload="false"
        ref="uploadRef"
        :on-remove="handleRemove"
        :on-change="uploadFile"
        :limit="3"
        :on-exceed="moreLimit"
        :file-list="fileList">
        <el-icon><Plus /></el-icon>
    </el-upload>
    <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image"/>
    </el-dialog>
</template>

<script setup lang="ts">
import {uploadImageApi} from '../api/img/index'
import { ref } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { type NewType }  from '../type/BaseType'
import { ElMessage,type UploadFile,type UploadUserFile,type UploadFiles } from 'element-plus'; 
//注册事件
const emits = defineEmits(['getImg'])
//图片上传的ref属性
const uploadRef = ref()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
type PropType = {
    fileList:UploadUserFile[]
    oldUrl:Array<{url:string}>
}
const props = withDefaults(defineProps<PropType>(),{
    fileList:()=>[],
    oldUrl:()=>[]
})
//返回给父组件的值
const newImgRes = ref<NewType>({
    newImgUrl:[],
    deleteUrl:[]
})
//删除图片
const handleRemove = (file:UploadFile)=>{
    if(props.oldUrl.some(item =>item.url === file.name)){
        newImgRes.value.deleteUrl.push({url:file.name})
        emits('getImg',newImgRes.value)
    }
}
//文件个数超出
const moreLimit = (files:File[],uploadFiles:UploadFiles)=>{
    console.log(files)
    ElMessage.warning("最多只能上传"+uploadFiles.length+"张图片")
}
const uploadFile = async(file:any)=>{
    const typeArr = ["image/png","image/jpeg","image/gif","image/jpg"]
    const isImg = typeArr.indexOf(file.raw.type) !== -1;
    const isMore3M = file.size / 1024 / 1024 <3;
if(!isImg){
    ElMessage.warning("只能上传图片类型");
    uploadRef.value?.clearFiles();
    return;
}  
if(!isMore3M){
    ElMessage.warning("图片大小不能超过3M");
    uploadRef.value?.clearFiles();
    return;
} 

//组装上传的数据
const formData = new FormData();
formData.append("file",file.raw);
const res = await uploadImageApi(formData)
if(res && res.code == 200 && res.data){
    ElMessage.success('图片上传成功')
    // file.name = process.env.BASE_API_IMG + res.data;
    file.name = 'http://localhost:8089' + res.data;
    newImgRes.value.newImgUrl.push({
        url:res.data
    })
    emits('getImg',newImgRes.value)
}
}
//清空数据
const clearimg = () =>{
    uploadRef.value?.clearFiles();
    newImgRes.value.deleteUrl=[];
    newImgRes.value.newImgUrl=[];
}
defineExpose({
    clearimg
})
</script>

<style lang="scss" scoped>

</style>